package com.ssy.lingxi.purchase.controller.tender;

import cn.hutool.core.bean.BeanUtil;
import com.ssy.lingxi.common.controller.BaseController;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.purchase.api.dto.request.tender.EvaluationTenderReportRequest;
import com.ssy.lingxi.purchase.api.dto.request.tender.SimpleIdRequest;
import com.ssy.lingxi.purchase.api.dto.response.tender.EvaluationInviteTenderDetailResponse;
import com.ssy.lingxi.purchase.api.dto.response.tender.EvaluationInviteTenderMemberResponse;
import com.ssy.lingxi.purchase.api.dto.response.tender.EvaluationTenderDetailResponse;
import com.ssy.lingxi.purchase.api.dto.response.tender.ExpertExtractRecordDetailResponse;
import com.ssy.lingxi.purchase.api.enums.tender.InviteTenderInStatusEnum;
import com.ssy.lingxi.purchase.api.enums.tender.InviteTenderOutStatusEnum;
import com.ssy.lingxi.purchase.entity.tender.*;
import com.ssy.lingxi.purchase.service.tender.IInviteTenderService;
import com.ssy.lingxi.purchase.service.tender.ITemplateService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @menu: 招投标-专家评标报告管理
 * 专家评标报告管理
 * @author jw.chen
 * @version 2.0.0
 * @date 2021/3/20
 */
@RestController
@RequestMapping("/purchase/expertExtractReport")
public class ExpertExtractReportController extends BaseController {

    @Resource
    private IInviteTenderService inviteTenderService;

    @Resource
    private ITemplateService templateService;

    /**
     * 查询提交评标报告
     * @param inviteTenderId 招标id
     */
    @RequestMapping(value = "/getEvaluationTenderReport", method = RequestMethod.GET)
    public Wrapper<EvaluationInviteTenderDetailResponse> getEvaluationTenderReport(@RequestParam("inviteTenderId") Long inviteTenderId) {
        InviteTender inviteTender = inviteTenderService.getInviteTender(inviteTenderId);
        if(inviteTender != null){
            //定义临时变量
            List<ExpertExtractRecordDetailResponse> expertExtractRecordDetailList = new ArrayList<>();
            List<EvaluationInviteTenderMemberResponse> evaluationInviteTenderMemberList = new ArrayList<>();
            HashMap<Long, EvaluationInviteTenderMemberResponse> memberEvaluationTenderMap = new HashMap<>();

            List<InviteTenderMember> memberList = inviteTender.getMemberList();
            memberList.forEach(inviteTenderMember -> {
                //只查询已经投标的会员
                Boolean isSubmit = inviteTenderMember.getIsSubmit();
                if (isSubmit) {
                    Long memberId = inviteTenderMember.getMemberId();
                    String memberName = inviteTenderMember.getMemberName();
                    EvaluationInviteTenderMemberResponse evaluationInviteTenderMember = new EvaluationInviteTenderMemberResponse();
                    evaluationInviteTenderMember.setId(memberId);
                    evaluationInviteTenderMember.setMemberId(memberId);
                    evaluationInviteTenderMember.setMemberName(memberName);
                    evaluationInviteTenderMember.setCorrectScore(inviteTenderMember.getCorrectScore());
                    memberEvaluationTenderMap.put(memberId, evaluationInviteTenderMember);
                    evaluationInviteTenderMemberList.add(evaluationInviteTenderMember);
                }
            });

            EvaluationInviteTenderDetailResponse evaluationInviteTenderDetail = BeanUtil.copyProperties(inviteTender, EvaluationInviteTenderDetailResponse.class);
            List<ExpertExtract> expertExtractList = inviteTender.getExpertExtractList();
            expertExtractList.forEach(expertExtract -> {
                List<ExpertExtractRecord> expertExtractRecordList = expertExtract.getExpertExtractRecordList();
                expertExtractRecordList.forEach(expertExtractRecord -> {
                    //投标会员（组装数据给前端）
                    List<EvaluationTenderOnline> evaluationTenderList = expertExtractRecord.getEvaluationTenderList();
                    evaluationTenderList.forEach(evaluationTender -> {
                        Long inviteTenderMemberId = evaluationTender.getInviteTenderMemberId();
                        EvaluationInviteTenderMemberResponse evaluationInviteTenderMember = memberEvaluationTenderMap.get(inviteTenderMemberId);
                        if(evaluationInviteTenderMember != null){
                            EvaluationTenderDetailResponse evaluationTenderDetailResponse = BeanUtil.copyProperties(evaluationTender, EvaluationTenderDetailResponse.class);
                            SimpleIdRequest simpleIdRequest = new SimpleIdRequest();
                            simpleIdRequest.setId(expertExtractRecord.getId());
                            evaluationTenderDetailResponse.setExpertExtractRecord(simpleIdRequest);

                            List<EvaluationTenderDetailResponse> evaluationTenderDetailResponseList = evaluationInviteTenderMember.getEvaluationTenderList();
                            if(evaluationTenderDetailResponseList == null){
                                evaluationTenderDetailResponseList = new ArrayList<>();
                            }
                            if(!evaluationTenderDetailResponseList.contains(evaluationTenderDetailResponse)){
                                evaluationTenderDetailResponseList.add(evaluationTenderDetailResponse);
                                evaluationInviteTenderMember.setEvaluationTenderList(evaluationTenderDetailResponseList);
                            }
                            memberEvaluationTenderMap.put(inviteTenderMemberId, evaluationInviteTenderMember);
                        }
                    });
                    //专家抽取记录
                    ExpertExtractRecordDetailResponse expertExtractRecordDetail = BeanUtil.copyProperties(expertExtractRecord, ExpertExtractRecordDetailResponse.class);
                    if(expertExtractRecordDetail != null && !expertExtractRecordDetailList.contains(expertExtractRecordDetail)){
                        expertExtractRecordDetailList.add(expertExtractRecordDetail);
                    }
                });
            });
            evaluationInviteTenderDetail.setExpertExtractList(expertExtractRecordDetailList);
            evaluationInviteTenderDetail.setMemberList(evaluationInviteTenderMemberList);

            //同一个专家对同一个会员的评分，按评分分类进行多个评分项的分数进行累加
            DecimalFormat decimalFormat = new DecimalFormat("#.00");
            evaluationInviteTenderMemberList.forEach(evaluationInviteTenderMemberResponse -> {
                List<EvaluationTenderDetailResponse> evaluationTenderList = evaluationInviteTenderMemberResponse.getEvaluationTenderList();
                if(evaluationTenderList != null && evaluationTenderList.size() > 0){
                    List<Double> correctScoreList = new ArrayList<>();
                    List<EvaluationTenderDetailResponse> newEvaluationTenderList = new ArrayList<>();
                    // 通过combination返回的字符串分组，为key,相同的专家 + 评分分类为列表
                    Map<String, List<EvaluationTenderDetailResponse>> collect = evaluationTenderList.stream().collect(Collectors.groupingBy(this::combination, Collectors.toList()));
                    collect.forEach((key,list)-> {
                        double sum = list.stream().mapToDouble(EvaluationTenderDetailResponse::getScore).sum();
                        EvaluationTenderDetailResponse evaluationTenderDetailResponse = list.get(0);
                        evaluationTenderDetailResponse.setScore(Double.parseDouble(decimalFormat.format(sum)));
                        newEvaluationTenderList.add(evaluationTenderDetailResponse);

                        correctScoreList.add(sum);
                    });
                    evaluationInviteTenderMemberResponse.setEvaluationTenderList(newEvaluationTenderList);

                    //如果有修正总分，以修正总分为准，没有的话，按各项的评分累加
                    Double correctScore = evaluationInviteTenderMemberResponse.getCorrectScore();
                    if(correctScore == null){
                        double sum = correctScoreList.stream().reduce(Double::sum).orElse(0D);
                        evaluationInviteTenderMemberResponse.setCorrectScore(Double.parseDouble(decimalFormat.format(sum)));
                    }
                }
            });

            evaluationInviteTenderDetail.setInviteTenderInStatusValue(InviteTenderInStatusEnum.getMessage(inviteTender.getInviteTenderInStatus()));
            evaluationInviteTenderDetail.setInviteTenderOutStatusValue(InviteTenderOutStatusEnum.getMessage(inviteTender.getInviteTenderOutStatus()));

            //查询评标模板名称
            Long templateId = inviteTender.getTemplateId();
            if(templateId != null && templateId > 0){
                Template template = templateService.getTemplate(templateId);
                if(template != null){
                    evaluationInviteTenderDetail.setTemplateName(template.getName());
                }
            }

            return Wrapper.success(evaluationInviteTenderDetail);
        }else{
            throw new BusinessException(ResponseCode.PURCHASE_INVITE_TENDER_NOT_EXIST);
        }
    }

    /**
     * 按专家 + 评分分类进行分组
     */
    private String combination(EvaluationTenderDetailResponse evaluationTenderDetailResponse){
        return evaluationTenderDetailResponse.getExpertExtractRecord().getId() + evaluationTenderDetailResponse.getSort();
    }

    /**
     * 提交评标报告
     * @param evaluationTenderReportRequest 参数
     */
    @RequestMapping(value = "/submitEvaluationTenderReport", method = RequestMethod.POST)
    public Wrapper<String> submitEvaluationTenderReport(@RequestBody EvaluationTenderReportRequest evaluationTenderReportRequest) {
        UserLoginCacheDTO sysUser = this.getSysUser();
        return Wrapper.success(inviteTenderService.submitEvaluationTenderReport(sysUser, evaluationTenderReportRequest));
    }
}
